Installing Libraries¶

In [ ]:
!pip install geopandas

Importing Libraries¶

In [ ]:
import numpy as np
import pandas as pd
import geopandas as gpd
!pip install folium
import folium
from folium import plugins
import datetime

from IPython.display import HTML, display

from folium.plugins import TimestampedGeoJson

Importing the data as Pandas DataFrame¶

In [ ]:
fp = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv"
eartt=pd.read_csv(fp)
eartt.head()

Rename the name of the column¶

In [ ]:
eartt1=eartt.rename({'time':'time_hour'}, axis=1)
eartt1.head()

The time is imported as text (strings)¶

In [ ]:
type(eartt1.loc[0,'time_hour'])

Changing time to datetime¶

In [ ]:
eartt1['time_hour']=eartt1['time_hour'].str[:-5]
eartt1['time_hour']=pd.to_datetime(eartt1['time_hour'])

Time as the data frame's index¶

Create a new column called "type" to help us in the pivoting¶

In [ ]:
eartt1=eartt1.set_index('time_hour')
eartt1['type']= 'ss'
eartt1.head(1)

List number of earquakes by place, time, location, magnitude¶

In [ ]:
start = eartt1.pivot_table('id',
                          index = ['place', 'time_hour',
                                   'latitude',
                                   'longitude',
                                   'mag'
                                   ],
                          columns = 'type',
                          aggfunc='count').reset_index()




start.head()

Extract the hour from time_hour¶

In [ ]:
start['time_hour']=pd.to_datetime(start['time_hour'])
start['time_hh']=start['time_hour'].dt.hour
start.head()

Choosing color depending on the magnitude for each Earthquake¶

3352FF Blue

FCFF33 Yellow

FF33EC Pink

FF334C Red

In [ ]:
start.loc[start['mag']<7, 'fillcolor']='#3352FF ' # Earthquakes with magnitude less than 7  = blue color
start.loc[start['mag']>=7, 'fillcolor']='#FF33EC' # Earthquakes with magnitude bigger or equal than 7  = pink color
start.loc[start['mag']>=8, 'fillcolor']='#FCFF33' # Earthquakes with magnitude bigger or equal than 8  = yellow color
start.loc[start['mag']>=9, 'fillcolor']='#FF334C' # Earthquakes with magnitude bigger or equal than 9  = red color
In [ ]:
start.shape
Out[ ]:
(9735, 8)
In [ ]:
start.head()
Out[ ]:
type place time_hour latitude longitude mag ss time_hh fillcolor
0 0 km E of Elmendorf Air Force Base, Alaska 2023-10-29 20:39:52 61.257200 -149.614300 1.30 1 20 #3352FF
1 0 km E of Hospital, Chile 2023-11-05 15:48:11 -20.214300 -70.132300 3.30 1 15 #3352FF
2 0 km E of Howardville, Missouri 2023-11-09 12:37:18 36.568333 -89.597000 1.61 1 12 #3352FF
3 0 km E of Indios, Puerto Rico 2023-11-07 10:02:52 17.994667 -66.811333 2.64 1 10 #3352FF
4 0 km ENE of Pāhala, Hawaii 2023-11-14 01:31:31 19.203167 -155.477829 1.84 1 1 #3352FF

Normalizing magnitude with max and min values¶

In [ ]:
start['mag']= (start['mag'] - start['mag'].min())/(start['mag'].max()-start['mag'].min())
#df["A"] = (df["A"]-df["A"].min()) / (df["A"].max()-df["A"].min())
start['mag'].head()

Function to create the features of the animation: time, location, icon to represent magnitude of Earthquake, etc¶

In [ ]:
def create_geojson_features(df):
    features = []

    for _, row in df.iterrows():
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['longitude'],row['latitude']]
            },
            'properties': {
                'time': pd.to_datetime(row['time_hour'], unit='h').__str__(),
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillcolor'],
                    'fillOpacity': 0.8,
                    'stroke': 'true',
                    'radius': row['mag']*10
                }
            }
        }
        features.append(feature)
    return features

Calling the Function create_geojson_features and using it in our data frame and get the geojson¶

In [ ]:
start_geojson = create_geojson_features(start)
start_geojson[0]

Creating Interactive And Animated Map¶

In [ ]:
EQ_map = folium.Map(location = [2, -2],
                    tiles = "CartoDB Positron",
                    zoom_start = 2)
plugins.ScrollZoomToggler().add_to(EQ_map)

icon_plane = plugins.BeautifyIcon(
    icon="plane", border_color="#b3334f", text_color="#b3334f", icon_shape="triangle"
)

icon_number = plugins.BeautifyIcon(
    border_color="#00ABDC",
    text_color="#00ABDC",
    number=10,
    inner_icon_style="margin-top:0;",
)



folium.Marker(location=[50, -122], popup="Portland, OR", icon=icon_number).add_to(EQ_map)

plugins.Fullscreen(
    position="topright",
    title="Expand me",
    title_cancel="Exit me",
    force_separate_button=True,
).add_to(EQ_map)


TimestampedGeoJson(start_geojson,
                  period = 'PT1H',
                  duration = 'PT1H',
                  transition_time = 1000,
                  auto_play = True).add_to(EQ_map)

EQ_map
Out[ ]:
Make this Notebook Trusted to load map: File -> Trust Notebook
In [ ]:
EQ_map.save('EQ_mapNew.html')
In [ ]: